#include "ResponderMediator.h"
#include  <vector>

ResponderMediator * ResponderMediator::create(IResponder * object)
{
	ResponderMediator * ret = new ResponderMediator();
	if (ret && ret->initialized(object))
	{
		ret->autorelease();
	}
	else
	{
		CC_SAFE_DELETE(ret);
	}
	return ret;
}

bool ResponderMediator::initialized(IResponder * object)
{
	this->_document = object;

	collectInterests();

	return true;
}

void ResponderMediator::collectInterests()
{
	std::vector<std::string> actions = _document->ListInterests();

	for(auto str : actions)
	{
		cocos2d::CCNotificationCenter::sharedNotificationCenter()->addObserver(this,
																				 callfuncO_selector(ResponderMediator::handleResponder),
																				str,
																				NULL);
	}
}

void ResponderMediator::handleResponder(Ref* obj)
{
	ResponderObject * object = dynamic_cast<ResponderObject*>(obj);

	this->_document->handleResponder(object);
}

void ResponderMediator::clean()
{
	std::vector<std::string> actions = _document->ListInterests();

	for (auto str : actions)
	{
		cocos2d::CCNotificationCenter::sharedNotificationCenter()->removeObserver(this,str);
	}
}

void ResponderMediator::dispatchEvent(const std::string & keyName , ResponderObject * object)
{
	object->mes_key_name = keyName;
	cocos2d::CCNotificationCenter::sharedNotificationCenter()->postNotification(keyName,object);
}